package com.dp.client.views.archivo;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.CaptionPanel;

public class SubirArchivo extends Composite
{
	public static final String UPLOAD_ACTION_URL = GWT.getModuleBaseURL()+"ISubirArchivo";
	
		public SubirArchivo(String nombre, final String num) 
		{	
			VerticalPanel v = new VerticalPanel();
			v.setSize("357px", "309px");
			initWidget(v);
			
			CaptionPanel upperPanel = new CaptionPanel();
			upperPanel.setCaptionText(nombre);
			v.add( upperPanel );
			upperPanel.setSize("auto", "auto");
			
			final FormPanel form = new FormPanel();
			form.setAction(UPLOAD_ACTION_URL+num);

			form.setEncoding(FormPanel.ENCODING_MULTIPART);
			form.setMethod(FormPanel.METHOD_POST);

			VerticalPanel panel = new VerticalPanel();
			form.setWidget(panel);

			final FileUpload upload = new FileUpload();
			upload.setName("uploadFormElement");
			panel.add(upload);
			upload.setHeight("23px");

			panel.add(new Button("Cargar", new ClickHandler() {
				@Override
				public void onClick(ClickEvent event) {
					form.submit();
				}
			}));

			form.addSubmitHandler(new FormPanel.SubmitHandler() {
				@Override
				public void onSubmit(SubmitEvent event) {
					Window.alert(""+upload.getFilename());
				}
			});

			form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
				@Override
				public void onSubmitComplete(SubmitCompleteEvent event) {
					if(!num.equals("5"))
						Window.alert(event.getResults());
					else{
						List<String> datos = new ArrayList<String>();
						String cad = "";
						char[] results = event.getResults().toCharArray();
						for(int i = 0; i < results.length; i++){
							if(results[i] == '\n'){
								datos.add(cad);
								cad = "";
							}else cad += results[i];
						}
						CargaDeRutas popup = new CargaDeRutas(datos);
						popup.center();
					}
				}
			});
			
			upperPanel.add(form);
		}
}

